package com.example.literj.kt.internal.schedulers

import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.ScheduledThreadPoolExecutor
import java.util.concurrent.ThreadFactory

class SchedulerPoolFactory {

    companion object {
        private val PURGE_ENABLED_KEY = "rx3.purge-enabled"

        private var PURGE_ENABLED = false

        init {
            val propertyAccessor = SystemPropertyAccessor()
            PURGE_ENABLED = getBooleanProperty(
                true, PURGE_ENABLED_KEY, true, true, propertyAccessor
            )
        }

        fun getBooleanProperty(
            enabled: Boolean,
            key: String,
            defaultNotFound: Boolean,
            defaultNotEnabled: Boolean,
            propertyAccessor: com.example.literj.kt.internal.functions.Function<String, String>
        ): Boolean {
            return if (enabled) {
                try {
                    val value = propertyAccessor.apply(key)
                    "true" == value
                } catch (ex: Throwable) {
                    defaultNotFound
                }
            } else defaultNotEnabled
        }

        @JvmStatic
        fun create(factory: ThreadFactory?): ScheduledExecutorService {
            val exec = ScheduledThreadPoolExecutor(1, factory)
            exec.removeOnCancelPolicy = PURGE_ENABLED
            return exec
        }

        internal class SystemPropertyAccessor :
            com.example.literj.kt.internal.functions.Function<String, String> {
            override fun apply(t: String): String {
                return System.getProperty(t)
            }
        }
    }
}